package vip.ola.code.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.ola.code.common.ctrl.BaseController;
import vip.ola.code.common.service.RpcCommonService;
import vip.ola.code.service.UserService;
import vip.ola.core.common.Exception.ServiceException;
import vip.ola.core.common.annotation.MethodLog;
import vip.ola.core.common.constant.RetEnum;
import vip.ola.core.common.domain.BizResponse;
import vip.ola.core.common.domain.PayResponse;
import vip.ola.core.common.util.IPUtility;
import vip.ola.core.entity.code.CodeUser;

import java.util.concurrent.TimeUnit;

import static vip.ola.core.common.constant.CacheKey.APP_TOKEN_TIMEOUT;
import static vip.ola.core.common.constant.CacheKey.CODE_APP_TOKEN;
import static vip.ola.core.common.constant.CodeConstant.CODE_STATUS_OK;

@RestController
@RequestMapping("/api/app")
public class AppController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(AppController.class);
    @Autowired
    private RpcCommonService rpcService;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录鉴权
     *
     * @return
     * @throws AuthenticationException
     */
    @RequestMapping(value = "/login")
    @MethodLog(remark = "登录监听")
    public ResponseEntity<?> auth() {
        String username = getStringRequired("name");
        String password = getStringRequired("pass");
        String googleCodeStr = getStringRequired("googleCode").trim();

        long googleCode;
        try {
            googleCode = Long.parseLong(googleCodeStr);
        } catch (Exception e) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_GOOGLECODE_NOT_MATCH));
        }
        // 判断商户
        CodeUser codeUser = rpcService.codeUserService.getByName(username);
        if (codeUser == null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.CODE_USER_NOT_EXIST));
        }
        if (CODE_STATUS_OK != codeUser.getStatus()) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.CODE_USER_STATUS_STOP));
        }
        // 验证谷歌验证码
        // boolean checkResult = checkGoogleCode(codeUser.getGoogleAuthSecret(), googleCode);
        // if (!checkResult) {
        //     return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_GOOGLECODE_NOT_MATCH));
        // }
        String token;
        try {
            token = userService.login(username, password);
        } catch (ServiceException e) {
            return ResponseEntity.ok(BizResponse.build(e.getRetEnum()));
        }
        JSONObject data = new JSONObject();
        data.put("ip", IPUtility.getClientIp(request));
        data.put("id", codeUser.getId());
        data.put("token", token);
        stringRedisTemplate.opsForValue().set(CODE_APP_TOKEN + token, "1", APP_TOKEN_TIMEOUT, TimeUnit.SECONDS);
        return ResponseEntity.ok(PayResponse.buildSuccess(data));
    }

    @RequestMapping(value = "/notify")
    @MethodLog(remark = "通知数据")
    public ResponseEntity<?> payNotify(@RequestBody JSONObject object) {
        String token = getStringRequired("token");
        String val = stringRedisTemplate.opsForValue().get(CODE_APP_TOKEN + token);
        if (StringUtils.isEmpty(val)) {
            return ResponseEntity.ok(PayResponse.build(-1, "无权限"));
        }
        logger.info(object.toJSONString());
        logger.info("-------------------");
        logger.info(JSONObject.toJSONString(request.getParameterMap()));
        String noticeType = getStringRequired("noticeType");
        String phoneId = getStringRequired("phoneId");
        String codeId = getStringRequired("codeId");
        String username = getStringRequired("username");
        String money = getStringRequired("money");
        String title = getStringRequired("title");
        String text = getStringRequired("text");
        System.out.println(title);
        System.out.println(text);
        // todo 回调逻辑
        stringRedisTemplate.opsForValue().set(CODE_APP_TOKEN + token, "1", APP_TOKEN_TIMEOUT, TimeUnit.SECONDS);
        return ResponseEntity.ok(PayResponse.buildSuccess());
    }

}
